package hms.reservations;

import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Iterator;

import hms.ReservationsModule.Guest;
import hms.database.DAO;
import hms.database.DAOnoGUI;
import hms.database.DBRowList;
import hms.rooms.Room;

public class ReservationView extends DBRowList<Reservation> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 2364785440060946111L;

	public ReservationView() {
		super();
	}
	
	/**
	 * Filter this view with all of the reservations during a given time.
	 * 
	 * @param fromDate
	 * @param toDate
	 */
	public void filterFromDateRange(Date fromDate, Date toDate) {
		
		Iterator<Reservation> i = iterator();
		while(i.hasNext()) {
			Reservation reservation = i.next();
			if(!(fromDate.before(reservation.getCheckOutDate()) &&
					toDate.after(reservation.getCheckInDate()))) {
				i.remove();
			}
		}
	}
	
	public void filterFromDateRange(Calendar fromDate, Calendar toDate) {
		filterFromDateRange(new Date(fromDate.getTimeInMillis()),new Date(toDate.getTimeInMillis()));
	}
	
	public void fillFromDateRange(Date fromDate, Date toDate) {
		fillFromDatabase();
		filterFromDateRange(fromDate,toDate);
	}
	
	public void fillFromDateRange(Calendar fromDate, Calendar toDate) {
		fillFromDatabase();
		  filterFromDateRange( fromDate,  toDate) ;
	}
	
	public Reservation nearestToToday() {
		Date today = new Date(new GregorianCalendar().getTimeInMillis());
		Reservation out = null;
		for(Reservation r : this) {
			if(out==null) {
				out = r;
			} else if(r.getCheckOutDate().after(today) && r.getCheckInDate().before(out.getCheckInDate())){
				out = r;
			}
		}
		return out;
	}

	public void fillForGuest(Guest guest) {
		DAO localDAO = DAOnoGUI.getDAO();
		
		ResultSet rs = localDAO.getResult("SELECT RESERVATION_ID FROM GUEST_RESERVATION WHERE GUEST_ID="+guest.getUniqueIdentifier()+";");
		try {
			while(rs.next()) {
				add(new Reservation(rs.getInt("RESERVATION_ID")));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		DAOnoGUI.closeDAO();
	}
	
	public void fillForRoomOnDate(Room room, Calendar c) {
		fillForRoomOnDate(room, new Date(c.getTimeInMillis()));
	}

	public void fillForRoomOnDate(Room room, Date d) {
		DAO localDAO = DAOnoGUI.getDAO();
		
		ResultSet rs = localDAO.getResult("SELECT RESERVATION_ID FROM ROOM_RESERVATION WHERE ROOMID="+room.getUniqueIdentifier()+";");
		try {
			while(rs.next()) {
				add(new Reservation(rs.getInt("RESERVATION_ID")));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		filterFromDateRange(d, d);
		
		DAOnoGUI.closeDAO();
	}
	
	@Override
	public void fillFromDatabase() {
		fillFromDatabase(Reservation.class);
	}

}
